from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.generics import ListCreateAPIView, ListAPIView, CreateAPIView
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from .models import ChatSession, ChatMessage
from .serializers import ChatSessionSerializer, ChatMessageSerializer


# 1. GET /api/chat/     POST /api/chat/
class ChatSessionListCreate(ListCreateAPIView):
    queryset = ChatSession.objects.all()
    serializer_class = ChatSessionSerializer

    def perform_create(self, serializer):
        # 自动生成标题
        title = f"对话 {ChatSession.objects.count() + 1}"
        serializer.save(title=title)


# 2. GET /api/chat/<id>/messages/
class MessageList(ListAPIView):
    serializer_class = ChatMessageSerializer

    def get_queryset(self):
        session = get_object_or_404(ChatSession, pk=self.kwargs["pk"])
        return session.messages.all()


# 3. POST /api/chat/<id>/messages/
class MessageCreate(CreateAPIView):
    serializer_class = ChatMessageSerializer

    def perform_create(self, serializer):
        session = get_object_or_404(ChatSession, pk=self.kwargs["pk"])
        message = serializer.save(session=session, role="user")

        # ===== 调扣子 API 拿 AI 回复 =====
        ai_content = call_coze_resume_agent(
            message.content, message.file
        )  # 替换成真实逻辑
        ChatMessage.objects.create(
            session=session, role="assistant", content=ai_content
        )


# 调扣子示例（占位）
def call_coze_resume_agent(content: str, file: str = None) -> str:
    """
    这里调用扣子 / OpenAI / 本地模型
    返回 Markdown 字符串
    """
    # TODO: 真实调用
    return f"**AI 回复**:\n- 您说：{content}\n- 文件：{file or '无'}"